package org.cometmi.gwt.echo3.client;

import org.cometmi.gwt.client.Connection;
import org.cometmi.gwt.echo3.shared.ServerTestProxy;
import org.cometmi.gwt.shared.MiQueue;
import org.cometmi.gwt.shared.MiQueuePool;
import org.cometmi.gwt.shared.events.BindCallback;
import org.cometmi.gwt.shared.exceptions.InvalidArgumentException;
import org.cometmi.gwt.shared.exceptions.NameParseException;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

public class Echo3Test implements EntryPoint
{
	Connection conn = Connection.INSTANCE;

	@Override
	public void onModuleLoad()
	{
		try
		{
			final MiQueue qListen = conn.getQueue("org.cometmi.gwt.test.echo3.client");
			MiQueuePool qSend = conn.getQueue("org.cometmi.gwt.test.echo3.server");

			final ServerTestProxy qq = qSend.proxyToObject(ServerTestProxy.class, "___id");

			qListen.bind(new BindCallback()
			{
				@Override
				public void onSuccess()
				{}

				@Override
				public void onError(Throwable t)
				{
					Window.alert(t.getMessage());
				}
			});

			final TextBox echoBox = new TextBox();

			Button sendButton = new Button("Send", new ClickHandler()
			{
				public void onClick(ClickEvent event)
				{
					try
					{
						qq.myMethod1(echoBox.getValue());
					}
					catch (InvalidArgumentException e)
					{}
				}
			});

			Button disconnect = new Button("disconnect", new ClickHandler()
			{
				@Override
				public void onClick(ClickEvent event)
				{
					qListen.unbind(new BindCallback()
					{
						@Override
						public void onSuccess()
						{
							Window.alert("Queue successfully disconnected.");
						}

						@Override
						public void onError(Throwable t)
						{
							Window.alert(t.getMessage());
						}
					}, true);
				}
			});

			RootPanel.get().add(echoBox);
			RootPanel.get().add(sendButton);
			RootPanel.get().add(disconnect);
		}
		catch (NameParseException e)
		{
			e.printStackTrace();
		}
	}
}
